import 'whatwg-fetch'

function checkStatus(response) {
  const statusText = response.statusText
  const statusCode = response.status
  if (statusCode >= 200 && statusCode < 300) {
    response.msg = '服务器请求成功'
    return response
  }
  if (statusCode === 500) {
    response.msg = '服务器请求超时，请重新刷新页面'
  }
  const error = new Error(statusText)
  error.response = response
  throw error
}

function parseJSON(response) {
  return response.json()
}

function fetchApi(url, setOptions) {
  return fetch(url, setOptions)
    .then(checkStatus)
    .then(parseJSON)
    .then((data) => {
      return data
    }).catch(error => {
      return error.response
    })
}

function requestGet(options) {
  let { url, method = 'GET', data } = options
  if (data) {
    let paramsArray = []
    Object.keys(data).forEach(key => paramsArray.push(key + '=' + data[key]))
    if (url.search(/\?/) === -1) {
      url += '?' + paramsArray.join('&')
    } else {
      url += '&' + paramsArray.join('&')
    }
  }
  const setOptions = {
    method: method,
    credentials: 'same-origin'
  }
  return fetchApi(url, setOptions)
}
export { requestGet }
